#c This file is part of WSAP web sockets server module.
# Copyright (c) 2010 Brandon Orther. All rights reserved.

from wsap_server.server import * 

class chat_server(server):
    """
    This is an example chat server.
    """

    user_cache = {}

    def log_on(self, fileno, data):
        # Setup user_cache and save nickname
        self.user_cache.setdefault(fileno,{})
        self.user_cache[fileno]["nickname"] = data["nickname"];

        # Notify others of new user logged in
        new_user = json_envelope.response("new_user", {"nickname": data["nickname"]})
        self.push(new_user, (fileno,))

        # Notify the user logged on successful
        return json_envelope.response("logged_on", {"nickname": data["nickname"]})

    def send_msg(self, fileno, data):
        # Push message to other users
        other_users_msg = json_envelope.response("get_others_msg", {"nickname": self.user_cache[fileno]["nickname"], "msg": data["msg"]})
        self.push(other_users_msg, (fileno,))
        # Send User Back His Message To Add To his Screen
        return json_envelope.response("get_own_msg", {"msg": data["msg"]})

if __name__ == "__main__":
    # Create and start server
    ts = chat_server("0.0.0.0", 9876, ["log_on","send_msg"])